# !/usr/bin/env python
# -*- coding: utf-8 -*-

import aioredis

from pydantic import BaseModel

from app.core.config import REDIS_URL


if not REDIS_URL:
    raise EnvironmentError("请检查环境变量中是否配置了redis的url！！")


class Redis(BaseModel):

    redis_url: str
    is_connected: bool = False
    # TODO 这里需要改进，配置为None 会被忽略掉
    global_connection = ""

    async def connect(self) -> None:
        assert not self.is_connected, "Redis Already connected."

        self.global_connection = await aioredis.create_redis_pool(self.redis_url)

        self.is_connected = True

    async def execute(self, command: str, *args, **kwargs):
        assert self.is_connected, "Redis unconnected."

        return await self.global_connection.execute(command, *args, **kwargs)

    async def close(self):
        self.global_connection.close()
        await self.global_connection.wait_closed()


red = Redis(redis_url=REDIS_URL)

